package com.supor.aiot.common.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;

import com.alibaba.fastjson.JSONObject;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.supor.aiot.common.R;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;

import java.lang.ref.WeakReference;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: SharePopUtils <br>
 * 作者: lei <br>
 * 日期: 2021/10/12 <br>
 */
public class SharePopUtils {

    static PopupWindow popupWindow;
    Handler handler;
    private WeakReference<Activity> activityReference;

    private static volatile SharePopUtils instance;
    private float alpha;
    int duration = 500;
    int sleepTime = duration / 100;
    Button popCancel;
    JSONObject param;
    boolean showWechat = true;
    boolean showWeibo = true;
    boolean showDouyin = true;
    boolean showCopyUrl = true;
    boolean isWechatInstall = true;
    boolean isWeiboInstall = true;
    boolean isDouyinInstall = true;
    boolean isCopyUrlExist = true;
    String shareUrl;
    ResultCallback resultCallback;

    public static SharePopUtils getInstance() {
        if (instance == null) {
            instance = new SharePopUtils();
        }
        return instance;
    }

    private SharePopUtils() {
    }

    /**
     * 是否显示微信和朋友圈分享
     *
     * @param show
     * @return
     */
    public SharePopUtils showWechat(boolean show) {
        showWechat = show;
        return this;
    }

    /**
     * 是否显示微博分享
     *
     * @param show
     * @return
     */
    public SharePopUtils showWeibo(boolean show) {
        showWeibo = show;
        return this;
    }

    /**
     * 是否显示抖音分享
     *
     * @param show
     * @return
     */
    public SharePopUtils showDouyin(boolean show) {
        showDouyin = show;
        return this;
    }

    /**
     * 设置分享结果监听，点击按钮即表示分享成功
     *
     * @param resultCallback
     * @return
     */
    public SharePopUtils setResultCallback(ResultCallback resultCallback) {
        this.resultCallback = resultCallback;
        return this;
    }

    /**
     * 是否显示复制链接
     *
     * @param show
     * @return
     */
    public SharePopUtils showCopyUrl(boolean show) {
        showCopyUrl = show;
        return this;
    }

    /**
     * 分享参数，详见README
     *
     * @param param
     * @return
     */
    public SharePopUtils params(JSONObject param) {
        this.param = param;
        return this;
    }

    public void initPop(Activity activity) {
        activityReference = new WeakReference<>(activity);

        handler = new Handler(activity.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    AnimationUtil.backgroundAlpha(activityReference.get(), (float) msg.obj);
                }
            }
        };
        popupWindow = new PopupWindow();
        View view = LayoutInflater.from(activity).inflate(R.layout.pop_share, null);
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);// 解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(false);// 点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.popup_window_anim);

        View wechat = view.findViewById(R.id.ll_wechat);
        View wechatPyq = view.findViewById(R.id.ll_wechat_pyq);
        View weibo = view.findViewById(R.id.ll_weibo);
        View douyin = view.findViewById(R.id.ll_douyin);
        View copyUrl = view.findViewById(R.id.ll_copy);

        view.findViewById(R.id.tv_wechat).setOnClickListener(v -> share(1));
        view.findViewById(R.id.tv_wechat_pyq).setOnClickListener(v -> share(2));
        view.findViewById(R.id.tv_weibo).setOnClickListener(v -> share(5));
        view.findViewById(R.id.tv_douyin).setOnClickListener(v -> share(7));
        view.findViewById(R.id.tv_copy).setOnClickListener(v -> share(8));

        if (!showWechat || !MarketUtils.getTools().isInstalled(activity, Constants.App.WeixinPackage)) {
            isWechatInstall = false;
            wechat.setVisibility(View.GONE);
            wechatPyq.setVisibility(View.GONE);
        }
        if (!showWeibo || !MarketUtils.getTools().isInstalled(activity, Constants.App.WeiboPackage)) {
            isWeiboInstall = false;
            weibo.setVisibility(View.GONE);
        }
        if (!showDouyin || !MarketUtils.getTools().isInstalled(activity, Constants.App.DouyinPackage)) {
            isDouyinInstall = false;
            douyin.setVisibility(View.GONE);
        }
        if (!showCopyUrl || TextUtils.isEmpty(this.param.getString(Constants.Key.param_shareUrl))) {
            isCopyUrlExist = false;
            copyUrl.setVisibility(View.GONE);
        }


        popCancel = view.findViewById(R.id.pop_cancel);

        popCancel.setOnClickListener(v -> popupWindow.dismiss());
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        // 退出popupWindow时取消暗背景
        popupWindow.setOnDismissListener(() -> ThreadUtils.execute(() -> {
            while (alpha < 1f) {
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                alpha += 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        }));
    }

    private void share(int type) {
        if (param != null) {
            param.put(Constants.Key.param_shareType, type);
        }
        // JSONObject jo = new JSONObject();
        // // 分享类型：0取消分享；1微信；2微信朋友圈；3 QQ好友；4 QQ空间；5微博；6支付宝；7抖音
        // jo.put(Constants.Key.param_shareType, 1);
        // // 分享方式：0x1-text，0x2-image，0x3-URL
        // jo.put(Constants.Key.param_type, 3);
        // // 分享标题
        // jo.put(Constants.Key.param_title, "苏泊尔涨厨艺");
        // // 分享内容描述
        // jo.put(Constants.Key.param_desc, "破壁料理机SP65S");
        // // URL连接
        // jo.put(Constants.Key.param_path, "www.supor.com");
        // // 分享图片使用 URL（imgUrl）
        // jo.put(Constants.Key.param_imageUrl, "www.supor.com");
        // // 自定义分享预览大图
        // jo.put(Constants.Key.param_bgImgUrl, "www.supor.com");
        // // 视频Url
        // jo.put(Constants.Key.param_videoUrl, "https://iot.mp4");
        SuporPresenter.getInstance().sendShareMsg(param);

        dismissPop();

        if (resultCallback != null) {
            resultCallback.onDismiss();
        }
    }

    /**
     * 显示弹框
     *
     * @param activity activity
     * @param rootView 根View
     */
    public void showPop(Activity activity, View rootView) {
        if (popupWindow == null) {
            initPop(activity);
        }
        if (!showWechat && !showWeibo && !showDouyin && !showCopyUrl) {
            return;
        }
        if (!isWeiboInstall && !isWechatInstall && !isDouyinInstall && !isCopyUrlExist) {
            return;
        }
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        alpha = 1f;
        ThreadUtils.execute(() -> {
            while (alpha > 0.5f) {
                try {
                    // 根据弹出动画时间和减少的透明度计算时间
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = 1;
                // 每次减少0.005，精度越高，变暗的效果越流畅
                alpha -= 0.005f;
                msg.obj = alpha;
                handler.sendMessage(msg);
            }
        });
    }

    public boolean isPopShow() {
        return popupWindow != null && popupWindow.isShowing();
    }

    public void dismissPop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    public interface ResultCallback {
        /**
         * 分享结束，销毁对话框
         */
        void onDismiss();
    }
}
